import React from 'react';
import ReactDOM from 'react-dom';
import BraftEditor, { EditorState } from 'braft-editor';
import { ContentUtils } from 'braft-utils';
import 'braft-editor/dist/index.css';

class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createFrom(),
    };
    this.editorInstance = null;
  }

  handleChange = editorState => {
    this.setState({ editorState });
  };

  insertText = text => {
    this.setState({
      editorState: ContentUtils.insertText(this.state.editorState, text),
    });
  };

  buildPreviewHtml = () => {
    console.log('editorState', this.state.editorState.toHTML());
    return this.state.editorState.toHTML();
  };

  uploadFn = param => {
    const xhr = new XMLHttpRequest();
    const fd = new FormData();

    const successFn = () => {
      param.success({
        url: JSON.parse(xhr.responseText)[0].url,
        meta: {
          controls: true,
          loop: true,
          autoPlay: false,
        },
      });
    };

    const progressFn = event => {
      param.progress((event.loaded / event.total) * 100);
    };

    const errorFn = () => {
      param.error({
        msg: 'unable to upload.',
      });
    };

    xhr.upload.addEventListener('progress', progressFn, false);
    xhr.addEventListener('load', successFn, false);
    xhr.addEventListener('error', errorFn, false);
    xhr.addEventListener('abort', errorFn, false);

    fd.append('file', param.file);
    xhr.open('POST', 'http://localhost:9090', true);
    xhr.send(fd);
  };

  hooks = {};

  render() {
    let that = this;
    const controls = BraftEditor.defaultProps.controls.map(item => {
      return item === 'bold'
        ? {
            key: 'bold', // 使用key来指定控件类型
            title: '加粗选中文字哦', // 自定义控件title
            text: '点我加粗', // 使用自定义文案来代替默认图标(B)，此处也可传入jsx
          }
        : item;
    });

    const extendControls = [
      'separator',
      {
        key: 'my-button', // 控件唯一标识，必传
        type: 'button',
        title: '这是一个自定义的按钮', // 指定鼠标悬停提示文案
        className: 'my-button', // 指定按钮的样式名
        html: null, // 指定在按钮中渲染的html字符串
        text: 'Preview', // 指定按钮文字，此处可传入jsx，若已指定html，则text不会显示
        onClick: () => {
          console.log('Hello World!');
          let editorHtml = that.buildPreviewHtml();
          console.log('editorHtml ==>', editorHtml);
          let dom = `<!DOCTYPE html>
          <html>
          <head>
          <meta charset="utf-8">
          <title>预览</title>
          <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
          <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
          <meta content="black" name="apple-mobile-web-app-status-bar-style">
          <meta name="format-detection" content="telephone=no">
          <meta name="format-detection" content="email=no">
          <meta name="apple-mobile-web-app-capable" content="yes">

          <style type="text/css">
            body,html {
              padding: 0;
              margin: 0 auto;
              -webkit-tap-highlight-color: rgba(255,255,255,0);
              background: #fff;
              color: #303030;
              width: 100%;
              font-family: Helvetica;
              -webkit-overflow-scrolling: touch;
              max-width: 640px;
          }
          .editor-container {
              padding: 0 .8rem;
              background: #fff;
              width: 100%;
              word-wrap: break-word;
              color: #606060;
              text-align: justify
          }
          .editor-container p {
            white-space: pre-wrap; // 处理空格不识别的问题
          }
          .editor-container img {
            max-width: 100%;
          }
          </style>
          </head>
          <body>
          <div class="editor-container">
          ${editorHtml}
          </div>
          </body>
          </html>`;
          const w = window.open('about:blank');
          w.document.write(dom);
        },
      },
    ];

    return (
      <div>
        <div className="demo" id="demo">
          <BraftEditor
            hooks={this.hooks}
            controls={controls}
            extendControls={extendControls}
            media={
              {
                // uploadFn: this.uploadFn
              }
            }
            onChange={this.handleChange}
            defaultValue={this.state.editorState}
          />
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Demo />, document.querySelector('#root'));
